package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.message.IotMsgNotifyData;
import com.zzyl.nursing.dto.message.IotMsgService;
import com.zzyl.nursing.mapper.DeviceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备数据Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-03
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 批量新增设备数据
     *
     * @param iotMsgNotifyData
     */
    @Override
    public void batchSaveDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        //1.通过设备id查询设备是否存在
        String deviceId = iotMsgNotifyData.getHeader().getDeviceId();
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceId));
        if (ObjectUtil.isEmpty(device)) {
            throw new BaseException("设备不存在");
        }
        //2.批量保存设备数据
        List<IotMsgService> services = iotMsgNotifyData.getBody().getServices();
        services.forEach(service -> {
            //获取属性集合
            Map<String, Object> properties = service.getProperties();
            if (CollectionUtil.isEmpty(properties)) {
                return;
            }
            //获取上报时间
            String eventTimeStr = service.getEventTime();
            LocalDateTime eventTimeLocalDateTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
            // 时区转换
            LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(eventTimeLocalDateTime);

            //定义空的集合用来封装设备数据
            List<DeviceData> deviceDataList=new ArrayList<>();

            properties.forEach((key, value) -> {
                //封装到DeviceData对象中
                DeviceData deviceData= BeanUtil.toBean(device, DeviceData.class);
                deviceData.setId(null);//目的是防止bean拷贝的执行数据拷贝，置空的话让数据库自增
                deviceData.setAccessLocation(device.getBindingLocation());
                deviceData.setFunctionId(key);
                deviceData.setDataValue(value.toString());
                deviceData.setAlarmTime(eventTime);
                //封装到List集合中
                deviceDataList.add(deviceData);
            });
            this.saveBatch(deviceDataList);


            //同步数据到redis缓存中
            redisTemplate.opsForHash().put(Constants.IOT_DEVICE_LAST_DATA,device.getIotId(), JSONUtil.toJsonStr(deviceDataList));
        });

    }
}
